package net.zjitc.link;

import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        int size = 0;
        //01 02
       Node<Student> first =  new Node<Student>(new Student("01","a"));
       Node<Student> last = first;
       size++;

       last.next = new Node<>(new Student("02","b"));
       last = last.next;
       size++;


       last.next=  new Node<>(new Student("03","c"));
       last = last.next;
        size++;


      //5个节点
        last.next=  new Node<>(new Student("04","c"));
        last = last.next;
        size++;


        last.next=  new Node<>(new Student("05","c"));
        last = last.next;
        size++;

        //2. 查找索引为2的节点的数据（1.一共有几个学生:使用size记录）
        int index;
        Scanner scanner = new Scanner(System.in);
       // index = scanner.nextInt();
        //Student student = getData(size, first, index);





        //3.在索引为2的位置添加一个学生002，
        System.out.println("输入插入的位置");
        index = scanner.nextInt();
       size= addIndex(size, first, last, index);



     /*   Node<Student> p = first;
        int size =1;
        if (p == null){
            size = 0;
        }
        while (p.next!= null){
             p = p.next;
             size++;
        }
*/


      //5个节点--》删除第三个节点

        System.out.println();
    }

    /**
     * 指定位置插入节点
     * @param size
     * @param first
     * @param last
     * @param index
     */
    private static int addIndex(int size, Node<Student> first, Node<Student> last, int index) {
        if (index<0 || index>size){
            throw new RuntimeException("所插入的位置越界");
        }
        // 插入到最后的位置？index = size;
        Node<Student> newNode = new Node<>(new Student("002","f"));
        if (index == size){
            last.next=  newNode;
            last = last.next;
            size++;
            return size;

        }
        //插入到最前面？index = 0;
        if (index == 0){
            newNode.next = first;
            first = newNode;
            size++;
            return size;
        }
        //插入到中间的位置？ 应该找到插入位置的前一个节点，
        Node<Student> p = first;
        for (int i = 0; i < index-1; i++) {
            p = p.next;
        }
        newNode.next =p.next;
        p.next = newNode;
        size++;
        return size;
    }

    private static Student getData(int size, Node<Student> first, int index) {
        if (index<0 || index>=size){
            throw new RuntimeException("所查询的元素越界");
        }
        Node<Student> p = first;
        for (int i = 0; i < index; i++) {
            p = p.next;
        }

        return p.data;
    }
}
